package com.doubao.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.common.result.Result;
import com.doubao.device.dto.DeviceSettingDTO;
import com.doubao.device.dto.request.DeviceSettingRequest;
import com.doubao.device.entity.SmartDevice;
import com.doubao.device.entity.UserDeviceSetting;
import com.doubao.device.mapper.SmartDeviceMapper;
import com.doubao.device.mapper.UserDeviceSettingMapper;
import com.doubao.device.service.UserDeviceSettingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 用户智能体设置服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserDeviceSettingServiceImpl extends ServiceImpl<UserDeviceSettingMapper, UserDeviceSetting> implements UserDeviceSettingService {

    private final SmartDeviceMapper deviceMapper;

    @Override
    @CacheEvict(value = "userDeviceSetting", key = "#userId + ':' + #request.deviceId")
    public Result<DeviceSettingDTO> saveOrUpdateSetting(Long userId, DeviceSettingRequest request) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        // 检查智能体是否存在
        SmartDevice device = deviceMapper.selectById(request.getDeviceId());
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        // 查询是否已有设置
        LambdaQueryWrapper<UserDeviceSetting> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDeviceSetting::getUserId, userId)
                .eq(UserDeviceSetting::getDeviceId, request.getDeviceId());

        UserDeviceSetting setting = getOne(queryWrapper, false);
        boolean isNew = false;

        if (setting == null) {
            // 创建新设置
            setting = new UserDeviceSetting();
            setting.setUserId(userId);
            setting.setDeviceId(request.getDeviceId());
            setting.setCreatedAt(LocalDateTime.now());
            isNew = true;
        }

        // 更新设置内容
        setting.setContextLength(request.getContextLength());
        setting.setTemperature(request.getTemperature());
        setting.setTopP(request.getTopP());
        setting.setTopK(request.getTopK());
        setting.setMaxTokens(request.getMaxTokens());
        setting.setFrequencyPenalty(request.getFrequencyPenalty());
        setting.setPresencePenalty(request.getPresencePenalty());
        setting.setUseVoice(request.getUseVoice());
        setting.setVoiceId(request.getVoiceId());
        setting.setSpeechRate(request.getSpeechRate());
        setting.setPitch(request.getPitch());
        setting.setVolume(request.getVolume());
        setting.setEnableAutoTTS(request.getEnableAutoTTS());
        setting.setExtJson(request.getExtJson());
        setting.setUpdatedAt(LocalDateTime.now());

        // 保存设置
        if (isNew) {
            save(setting);
        } else {
            updateById(setting);
        }

        // 转换为DTO返回
        DeviceSettingDTO dto = convertToDTO(setting);
        return Result.success(dto);
    }

    @Override
    @Cacheable(value = "userDeviceSetting", key = "#userId + ':' + #deviceId", unless = "#result.data == null")
    public Result<DeviceSettingDTO> getUserDeviceSetting(Long userId, Long deviceId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        // 查询用户设置
        UserDeviceSetting setting = baseMapper.selectByUserAndDevice(userId, deviceId);

        if (setting == null) {
            // 如果没有用户设置，返回默认设置
            return getDefaultSetting(deviceId);
        }

        DeviceSettingDTO dto = convertToDTO(setting);
        return Result.success(dto);
    }

    @Override
    @CacheEvict(value = "userDeviceSetting", key = "#userId + ':' + #deviceId")
    public Result<Void> deleteSetting(Long userId, Long deviceId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }

        LambdaQueryWrapper<UserDeviceSetting> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserDeviceSetting::getUserId, userId)
                .eq(UserDeviceSetting::getDeviceId, deviceId);

        boolean removed = remove(queryWrapper);
        if (!removed) {
            return Result.failed("删除设置失败");
        }

        return Result.success();
    }

    @Override
    @Cacheable(value = "deviceDefaultSetting", key = "#deviceId", unless = "#result.data == null")
    public Result<DeviceSettingDTO> getDefaultSetting(Long deviceId) {
        // 查询智能体
        SmartDevice device = deviceMapper.selectById(deviceId);
        if (device == null) {
            return Result.failed("智能体不存在");
        }

        // 创建默认设置
        DeviceSettingDTO dto = new DeviceSettingDTO();
        dto.setDeviceId(deviceId);

        // 设置默认值
        dto.setContextLength(device.getMaxContextLength() != null ? device.getMaxContextLength() : 10);
        dto.setTemperature(BigDecimal.valueOf(0.7)); // 修复：将double转为BigDecimal
        dto.setTopP(BigDecimal.valueOf(0.9));       // 同理修复其他BigDecimal字段
        dto.setTopK(40);
        dto.setMaxTokens(2000);
        dto.setFrequencyPenalty(0.0);
        dto.setPresencePenalty(0.0);
        dto.setUseVoice(false);
        dto.setVoiceId(device.getVoiceId());
        dto.setSpeechRate(1.0);
        dto.setPitch(1.0);
        dto.setVolume(1.0);
        dto.setEnableAutoTTS(false);

        return Result.success(dto);
    }

    /**
     * 将实体转换为DTO
     */
    private DeviceSettingDTO convertToDTO(UserDeviceSetting setting) {
        DeviceSettingDTO dto = new DeviceSettingDTO();
        BeanUtils.copyProperties(setting, dto);
        return dto;
    }
}